const express = require('express');
const router = express.Router();
const GoodsCategory = require('../models/GoodsCategory');

// 统一响应格式函数
const sendResponse = (res, code = 200, message = 'success', data = null, total = null) => {
  const response = {
    code,
    message,
    data
  };
  
  if (total !== null) {
    response.total = total;
  }
  
  res.status(code).json(response);
};

// 统一错误响应函数
const sendError = (res, code = 500, message = '服务器内部错误', error = null) => {
  console.error('API错误:', error);
  res.status(code).json({
    code,
    message,
    data: null
  });
};

// 获取全部商品分类
router.get('/', async (req, res) => {
  try {
    const { name } = req.query;
    let result;
    
    if (name) {
      // 如果提供了名称参数，进行模糊查找
      result = await GoodsCategory.searchByName(name);
    } else {
      // 否则获取全部分类
      result = await GoodsCategory.getAllCategories();
    }
    
    sendResponse(res, 200, 'success', result.list, result.total);
  } catch (error) {
    sendError(res, 500, '获取商品分类失败', error);
  }
});

// 获取分类选项（用于下拉选择）
router.get('/options', async (req, res) => {
  try {
    const options = await GoodsCategory.getCategoryOptions();
    sendResponse(res, 200, 'success', options);
  } catch (error) {
    sendError(res, 500, '获取分类选项失败', error);
  }
});

// 获取单个商品分类详情
router.get('/:id', async (req, res) => {
  try {
    const categoryId = req.params.id;
    const result = await GoodsCategory.getById(categoryId);
    
    if (!result) {
      return sendError(res, 404, '商品分类不存在');
    }
    
    sendResponse(res, 200, 'success', result);
  } catch (error) {
    sendError(res, 500, '获取商品分类详情失败', error);
  }
});

// 创建新商品分类
router.post('/', async (req, res) => {
  try {
    const result = await GoodsCategory.create(req.body);
    sendResponse(res, 201, '商品分类创建成功', result);
  } catch (error) {
    if (error.message.includes('必填项')) {
      sendError(res, 400, error.message, error);
    } else {
      sendError(res, 500, '创建商品分类失败', error);
    }
  }
});

// 更新商品分类
router.put('/:id', async (req, res) => {
  try {
    const categoryId = req.params.id;
    const success = await GoodsCategory.update(categoryId, req.body);
    
    if (!success) {
      return sendError(res, 404, '商品分类不存在或更新失败');
    }
    
    sendResponse(res, 200, '商品分类更新成功');
  } catch (error) {
    if (error.message.includes('不存在') || error.message.includes('没有提供')) {
      sendError(res, 400, error.message, error);
    } else {
      sendError(res, 500, '更新商品分类失败', error);
    }
  }
});

// 删除商品分类
router.delete('/:id', async (req, res) => {
  try {
    const categoryId = req.params.id;
    const success = await GoodsCategory.delete(categoryId);
    
    if (!success) {
      return sendError(res, 404, '商品分类不存在或删除失败');
    }
    
    sendResponse(res, 200, '商品分类删除成功');
  } catch (error) {
    if (error.message.includes('不存在') || error.message.includes('无法删除')) {
      sendError(res, 400, error.message, error);
    } else {
      sendError(res, 500, '删除商品分类失败', error);
    }
  }
});

module.exports = router;
